#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use File::Spec;

#my @files = qw(CJB4 CJB5-2 CJB7 JEL289 JEL627 SRS812 TST75 JAM81 JEL423);
#my @genomes = qw(JEL423 JAM81);

my (%strains,%genomes);
my $basedir = '/project/batrachochytrium/popgen/analysis/Mosaik';
my $mosaik_tmp = "/scratch/mosaik";
my $key_size = 12;
my $cpus = 12;
GetOptions(
	   'd|dir:s' => \$basedir,
	   'cpus:i'  => \$cpus,
	   'ks|key:s'=> \$key_size,
	   );
my $strainsdir= File::Spec->catdir($basedir,'strains');
my $genomesdir= File::Spec->catdir($basedir,'genomes');
if( ! -d $strainsdir || ! -d $genomesdir ) {
    die "must provide a basedir that has a 'strains' and a 'genomes' directory\n";
}
opendir(STRAINS,$strainsdir) || die $!;
for my $st ( readdir(STRAINS) ) {
    if( $st =~ /(\S+)\.traces/) {
	$strains{$1} = File::Spec->catfile($strainsdir,$st);
    }
}
opendir(GENOMES,$genomesdir) || die $!;
for my $st ( readdir(GENOMES) ) {
    if( $st =~ /(\S+)_ref.dat/) {
	$genomes{$1} = File::Spec->catfile($genomesdir,$st);
	mkdir("$basedir/$1");
    }
}

for my $strain ( keys %strains ) {
    for my $genome ( keys %genomes ) {
	open(OUT, ">mosaikmap_$strain.$genome.sh");
	print OUT "#!/bin/bash\n";
	print OUT "cd $basedir\n";
	print OUT "export MOSAIK_TMP=$mosaik_tmp\n";
	print OUT "mkdir -p \$MOSAIK_TMP\n";
	
	print OUT "MosaikAligner -in $strains{$strain} -out $strain.$genome.aligned.dat -ia $genomes{$genome} -hs $key_size -j $genomesdir/$genome\_$key_size -rur $strain.$genome.unaligned.fq -p $cpus -act 22 -mm 7 -minp 0.14 -bw 17 -mmal\n";
	print OUT "MosaikSort -in $strain.$genome.aligned.dat -out $strain.$genome.aln_sort.dat\n";
	print OUT "MosaikAssembler -ia $genomes{$genome} -in $strain.$genome.aln_sort.dat -out $genome/$strain -f gig\n";
    }
}

